<?php

namespace beepay\demo;

use beepay\BeepayClient;
use beepay\BeepayConfig;
use beepay\Exception;
use beepay\util\BeepayKit;

class PayDemo
{
    /**
     * @var BeepayClient $client
     */
    private $client;

    public function __construct(BeepayClient $client)
    {
        $this->client = $client;
    }

    /**
     * 创建支付订单
     *
     * @return void
     */
    public function payOrderCreate()
    {
        $orderNo = 'mho' . time();
        try {
            $response = $this->client
                ->payOrderCreate()
                ->withMchNo(BeepayConfig::$mchNo)
                ->withAppId(BeepayConfig::$appId)
                ->withMchOrderNo($orderNo)
                ->withWayCode('ALI_QR')
                ->withAmount(1)
                ->withCurrency('CNY')
                ->withClientIp('192.166.1.132')
                ->withSubject('商品标题')
                ->withBody('商品描述')
                ->withNotifyUrl('https://mgr.pkzsl.com/api/anon/paytestNotify/payOrder')
                ->request();

            $checkSign = BeepayKit::checkSign($response['data'], $response['sign'], BeepayConfig::$apiKey);
            printf('验签结果：%s' . PHP_EOL, $checkSign ? '成功' : '失败');

            if ($response['code'] == 0 && $response['data'] && $checkSign) {
                printf('payOrderId：%s' . PHP_EOL, $response['data']['payOrderId']);
                printf('mchOrderNo：%s' . PHP_EOL, $response['data']['mchOrderNo']);
            } else {
                printf('下单失败：%s' . PHP_EOL, $orderNo);
                printf('通道错误码：%s' . PHP_EOL, $response['data']['errCode']);
                printf('通道错误信息：%s' . PHP_EOL, $response['data']['errMsg']);
            }
        } catch (Exception $e) {
            echo $e->getTraceAsString();
        }
    }

    /**
     * 查询支付订单
     * @return void
     */
    public function payOrderQuery()
    {
        try {
            $response = $this->client
                ->payOrderQuery()
                ->withMchNo(BeepayConfig::$mchNo)
                ->withAppId(BeepayConfig::$appId)
                ->withPayOrderId('P1516376483965747201')
                ->request();
            $checkSign = BeepayKit::checkSign($response['data'], $response['sign'], BeepayConfig::$apiKey);
            printf('验签结果：%s' . PHP_EOL, $checkSign ? '成功' : '失败');

            if ($response['code'] == 0 && $response['data'] && $checkSign) {
                printf('订单信息：%s' . PHP_EOL, print_r($response['data'], 1));
                printf('订单金额：%s' . PHP_EOL, '¥' . $response['data']['amount']);
            }
        } catch (Exception $e) {
            echo $e->getTraceAsString();
        }
    }
}